package git.luohao.util;

import com.alibaba.fastjson.JSON;
import git.luohao.entity.RouteDefinitionEntity;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;

import java.net.URI;
import java.util.*;

public class RouteUtil {

    public static List<RouteDefinition> convertToRouteDefinitionList(List<RouteDefinitionEntity> entityList) {
        List<RouteDefinition> routeDefinitionList = new ArrayList<>();
        for(RouteDefinitionEntity m : entityList) {
            RouteDefinition routeDefinition = convertToRouteDefinition(m);
            routeDefinitionList.add(routeDefinition);
        }
        return routeDefinitionList;
    }

    public static RouteDefinition convertToRouteDefinition(RouteDefinitionEntity entity) {
        RouteDefinition routeDefinition = new RouteDefinition();
        routeDefinition.setOrder(NonUtil.isNon(entity.getRouteOrder()) ? 0 : entity.getRouteOrder());
        routeDefinition.setUri(URI.create(entity.getUri()));
        routeDefinition.setId(entity.getRouteId());
        routeDefinition.setPredicates(Optional.ofNullable(entity.getRouterPredicates())
                .map(k -> JSON.parseArray(k, PredicateDefinition.class))
                .orElse(new ArrayList<>()));
        routeDefinition.setFilters(Optional.ofNullable(entity.getRouterFilters())
                .map(k -> JSON.parseArray(k, FilterDefinition.class))
                .orElse(new ArrayList<>()));
        routeDefinition.setMetadata(Optional.ofNullable(entity.getMetadata())
                .map(k -> JSON.parseObject(k, Map.class)).orElse(new HashMap<String, Object>()));
        return routeDefinition;
    }
}
